import axios from 'axios'
import store from "@/store";
import router from "@/router";
import {Message,Loading} from "element-ui"
import qs from "qs"
// 设置默认内容格式
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_URL,
    timeout: 10000
});

let tokenExists = ()=>{
    let token = store.getters.token;
    return  token !== undefined && token !== null && token.trim() !== "" &&  token !== "null" && token !== "undefined";
}
let loadingInstance;

let showLoading = (config) =>{
    if(config.method.toUpperCase() !== 'GET'){
        loadingInstance = Loading.service({ fullscreen: true ,text: "处理中..."});
   }
};
let closeLoading = () => {
    if(loadingInstance != null){
        loadingInstance.close();
    }
}

let addRequestTimestamp = (config) =>{
    if (config.method === 'post') {
        config.data = {
            ...config.data,
            _t: Date.parse(new Date()) / 1000
        }
    } else if (config.method === 'get') {
        config.params = {
            _t: Date.parse(new Date()) / 1000,
            ...config.params
        }
    }
}

service.interceptors.request.use(config=>{
    showLoading(config);
    let authorization = config.headers["Authorization"];
    if(!authorization && tokenExists()){
        config.headers["Authorization"] = 'Bearer ' + store.getters.token;
    }
    addRequestTimestamp(config);
    config.paramsSerializer = params => {
        return qs.stringify(params);
    }
    return config;
});

service.interceptors.response.use(response =>{
    closeLoading();
    if(response.data && response.data.status && response.data.status !== "1"){
        Message.error(response.data.message);
        return Promise.reject(response.data);
    }
    return response.data;
},error => {
    closeLoading();
    if(error.response.status === 401){
        if(!error.response.data.error){
            store.commit("clearToken");
            router.replace({
                path: '/login',
                query: {redirect: router.currentRoute.fullPath}
            }).then(()  => {})
        }
    }else if(error.response.status === 403){
        Message.error("无权限访问");
    }else if(error.response.status === 404){
        Message.error("资源不存在");
    }else if(error.response.status === 500){
        Message.error("服务器繁忙");
    }
    return Promise.reject(error);
})

export default service;